package com.yonyou.brigade.facade.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.facade.service.ISSOService;
import com.yonyou.brigade.facade.util.HttpReq;
import com.yonyou.brigade.facade.util.YYSpaceUtil;
import com.yonyou.brigade.rtpnr.service.IRtpnrUserService;
import com.yonyou.brigade.third_parties.ctrip.model.CtripConfig;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Service
public class SSOServiceImpl implements ISSOService {
    private static final Logger logger = LoggerFactory.getLogger(SSOServiceImpl.class);

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("rtpnrUserServiceImpl")
    private IRtpnrUserService rtpnrUserService;

    @Autowired
    private PropUtil propUtil;

    @Autowired
    private YYSpaceUtil yySpaceUtil;

    @Value("${yyspace.domain}")
    private String YYSPACE_DOMAIN;
    // 获取USERINFO
    private static final String URI_USERINFO_CODE="/certified/userInfo/";

    public String getSSOUrl(String third, String channel, String phone,String tenant)
    {
        String url="";
        UcUserDto ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(phone,tenant);
        if(ucUserDto==null)
        {
            throw new BusinessException("无法获取用户信息");
        }
        checkOpenInfo(third,tenant,ucUserDto.getOrgPk(),phone);
        if(third.equals(ChannelEnum.CTRIPBC.getName()))
        {

            if(channel.equals("flight"))
            {
                channel="FlightSearch";
            }
            else if(channel.equals("hotel"))
            {
                channel="HotelSearch";
            }
            else if(channel.equals("train"))
            {
                channel="TrainSearch";
            }

            url=propUtil.getPROJECT_URL()+"/thirdparties/ctrip/bigcustomer/ctripBCUser/ssomobilectrip?";
            url+="pCode="+ucUserDto.getPersonCode();
            url+="&orgPk="+ucUserDto.getOrgPk();
            url+="&tenant="+tenant;
            url+="&initPage="+channel;
        }
        else
        {

        }
        return  url;
    }
    /**
     * @Description: 获取友商旅（中航易购）单点地址
     * @param code 友空间带来的用户授权登录key
     * @Return: loginUrl 单点URL
     * @Date: 2018/9/26 11:34
     */
    @Override
    public String getRtpnrSSOUrl(String code) {
        String loginUrl = propUtil.getNO_ACCESS_URL();
        TreeMap<String, String> params = new TreeMap<>();
        params.put("code", code);
        params = yySpaceUtil.genParams(URI_USERINFO_CODE + code, params);
        try {
            String result = HttpReq.sendGet(YYSPACE_DOMAIN + URI_USERINFO_CODE + code, params);
            JSONObject resultObj = JSON.parseObject(result);
            int resultCode = resultObj.getInteger("code");
            if(0 == resultCode) {
                JSONObject dataObj = resultObj.getJSONObject("data");
                String phone = dataObj.getString("mobile");
                String tenantId = dataObj.getString("tenant_id");
                UcUserDto ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(phone, tenantId);
                loginUrl = rtpnrUserService.loginUrl(tenantId, ucUserDto.getOrgPk(), ucUserDto.getPhone(), "main", "h5","");
            }
            else {
                logger.error("友空间查询用户信息返回错误："+resultObj);
            }
        } catch (Exception e) {
            logger.error("友空间查询用户信息异常", e);
        }
        return loginUrl;
    }

    private void checkOpenInfo(String third,String tenant,String orgPk,String phone)
    {
        Map result=new HashMap();
        if(third.equals(ChannelEnum.CTRIPBC.getName()))
        {
            CtripConfig config=(CtripConfig) briChannelService.getChannelConfig(tenant,ChannelEnum.CTRIPBC.getName(),orgPk,new CtripConfig());
            if(config==null)
            {
                throw new BusinessException("当前组织尚未开通该服务");
            }

        }
        return;
    }
}
